/**
 * Created by YHB on 2015/6/26.
 */
define(['backbone', 'model/new', 'text!../../tpl/nav.html', 'text!../../tpl/new/newType.html', 'text!../../tpl/new/newlist.html', 'util/tip', 'config'],
    function (Backbone, newModel, navTemplate, newTypeTemplate, template, tip, CONSTANT) {
    var NewTypeView = Backbone.View.extend({

        el: '#view-container',

        initialize: function (options) {
            this.tid = parseInt(options.tid || 0);
            $(window).on('scroll', $.proxy(this.scrollHander, this));
        },

        render: function () {
            var nav = [{
                title: CONSTANT.AREA[this.tid],
                href: '#/newtype/' + this.tid
            }];
            this.$el.html(_.template(navTemplate)(nav)); //现将导航渲染

            var otherNav = [];
            for(var p in CONSTANT.AREA){
                if(p != this.tid){
                    otherNav.push({
                        area: p,
                        title: CONSTANT.AREA[p]
                    });
                }
            }
            this.$el.append(_.template(newTypeTemplate)(otherNav)); //现将导航渲染

            this.count = 10;

            this.loadCount();

            this.loadData(0, 10);
        },


        loadCount: function () {
            var query = new Bmob.Query(newModel);
            query.equalTo("area", this.tid);
            query.count({
                success: function(count) {
                    this.count = count;
                },
                error: function(error) {
                }
            });
        },

        loadData: function (skip, limit) {
            if(skip > this.count) return;
            this.skip = skip || 0;
            this.limit = limit || 10;
            var self = this;
            var query = new Bmob.Query(newModel);
            tip.showTip('加载中...', true);
            query.equalTo("area", this.tid);
            query.descending("updatedAt");
            query.skip(this.skip);
            query.limit(this.limit);
            query.find({
                success: function(results) {
                    self.template = _.template(template);
                    self.$el.append(self.template(results));
                    tip.hideTip();
                    return self;
                },
                error: function(error) {
                    tip.hideTip();
                    return self;
                }
            });
        },

        scrollHander: function () {
            var $win = $(window);
            var scrollTop = $win.scrollTop();
            var scrollHeight = $(document).height();
            var windowHeight = $win.height();
            if(scrollTop + windowHeight == scrollHeight){
                this.loadData(this.skip + this.limit, this.limit);
            }
        }
    });
    return NewTypeView;
});
